package worker

import (
	"context"
	"errors"
	"fmt"
	"time"

	jsoniter "github.com/json-iterator/go"
	"zhonghui/console/service"
	"zhonghui/console/structs"
	"zhonghui/console/warehouse/dbx"
	"zhonghui/console/warehouse/dbx/cache_main"
	"zhonghui/console/warehouse/dbx/db_zh_kernel_slave"
	"zhonghui/console/warehouse/helperx"
	"zhonghui/console/warehouse/logx"
	"zhonghui/console/warehouse/modelx/model_zh_kernel"
)

// ChartsDownloadWorker 报表缓存下载
type ChartsDownloadWorker struct {
}

func (w *ChartsDownloadWorker) Start() {
	w.do()
	t := time.NewTicker(60 * time.Minute)
	for {
		select {
		case <-t.C:
			w.do()
		}
	}
}

func (w *ChartsDownloadWorker) do() {
	defer func() {
		if r := recover(); r != nil {
			logx.Zap().Errorw("定时任务异常", "err", errors.New(fmt.Sprintf("%s", r)))
		}
	}()

	rc := cache_main.Client()
	lock, ch, err := dbx.GetRedisLockWithRefresh(rc, dbx.RedisPrefix("locker-ChartsDownloadWorker"), 30*time.Second, time.Second)
	if err != nil {
		return
	}
	defer func() {
		if ch != nil {
			ch <- 1
		}
		_ = lock.Release(context.Background())
	}()

	c := helperx.MakeCtxWithRequestId()

	allData := make([]structs.TaskChartsDownload, 0)
	cacheData := cache_main.Client().Get(c, "charts_download_cache").Val()
	if cacheData != "" && cache_main.Client().TTL(c, "charts_download_cache").Val().Hours() > 6 {
		return
	}

	tasks := make([]model_zh_kernel.SysTask, 0)
	db_zh_kernel_slave.ClientCtx(c).Where("status = ? and count >= 1000", structs.TaskStatusCompleted).Order("id asc").Find(&tasks)

	for _, task := range tasks {
		// 模板消息
		tp := model_zh_kernel.SysSmsTemplate{}
		db_zh_kernel_slave.Client().Where("template_id = ?", task.SmsTemplate).Take(&tp)
		if tp.ID == 0 {
			continue
		}

		data := structs.TaskChartsDownload{
			Task: task,
			Tp:   tp,
		}

		// 点击数据
		data.ClickCharts = service.GetClickDataForTask(&task)
		if task.CountSuccess > 0 {
			data.ClickCharts.ClickRate = helperx.NiceRate(float64(data.ClickCharts.Total) / float64(task.CountSuccess))
		} else {
			data.ClickCharts.ClickRate = "0%"
		}

		time.Sleep(time.Second)

		// 小程序数据
		data.MpCharts = service.GetMpDataForTask(&task)
		if data.Task.CountSuccess > 0 {
			data.MpCharts.MpRate = helperx.NiceRate(float64(data.MpCharts.Total) / float64(data.Task.CountSuccess))
		} else {
			data.MpCharts.MpRate = "0%"
		}

		time.Sleep(time.Second)

		// 企微数据
		data.WeComCharts = service.GetWeComDataForTask(&task)
		if data.Task.CountSuccess > 0 {
			data.WeComCharts.WeComRate = helperx.NiceRate(float64(data.WeComCharts.Total) / float64(data.Task.CountSuccess))
		} else {
			data.WeComCharts.WeComRate = "0%"
		}

		time.Sleep(time.Second)

		// 投保成功页面访问
		data.InsurancePolicyCharts = service.GetInsurancePolicyDataForTask(&task)
		if data.Task.CountSuccess > 0 {
			data.InsurancePolicyCharts.PolicyRate = helperx.NiceRate(float64(data.InsurancePolicyCharts.Total) / float64(data.Task.CountSuccess))
		} else {
			data.InsurancePolicyCharts.PolicyRate = "0%"
		}

		time.Sleep(time.Second)

		allData = append(allData, data)
	}

	j, _ := jsoniter.MarshalToString(allData)
	cache_main.Client().Set(c, "charts_download_cache", j, time.Hour*6).Val()
}
